package com.boot.config;

import com.boot.security.LoginFailureHandler;
import com.boot.security.LoginSuccessHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;

/**
 * @EnableWebSecurity:SpringSecurity的配置类 开启SpringSecurity【自带大量过滤器链:责任链模式】
 */
@Configuration //
@EnableWebSecurity //5.x中@EnableWebSecurity自带@Configuration
public class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        //authorizeHttpRequests:针对http请求进行授权,第一个过滤器
        http.authorizeHttpRequests(authorizeHttpRequests -> authorizeHttpRequests
                //login登录接口需要匿名访问
                // permitAlL:具有所有权限 也就可以匿名可以访问
                .requestMatchers("/login").permitAll()
                //anyRequest:任何请求 所有请求
                //authenticated:认证[登录]
                .anyRequest().authenticated()
        );
        //登录过滤器
        http.formLogin(formLogin -> formLogin.loginProcessingUrl("/login").permitAll() //登录页面
                .successHandler(new LoginSuccessHandler())
                .failureHandler(new LoginFailureHandler())
        );

        http.csrf(AbstractHttpConfigurer::disable); //关闭跨域漏洞攻击防护
        http.cors(AbstractHttpConfigurer::disable);//跨域拦截关闭

//        http.logout(logout -> logout.deleteCookies("JSESSIONID").invalidateHttpSession(true).logoutSuccessUrl("/index")) //退出登录接口
        return http.build();
    }
}
